/**
 * CS543 HW4 Joseph Meyer
 */
package edu.src.address;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Convience utilities for the AddressReader
 */
public class AddressReaderUtils {
	
	/**
	 * Bitmask to use for finding the offset of a 32 bit integer 
	 */
	public static int MASK_OFFSET = 255;
	
	/**
	 * Bitmask to use for finding the pageby of a 32 bit integer.
	 */
	public static int MASK_PAGEBY = 65280;
	
	/**
	 * Give a file, get a list of 32 integers.
	 * @param f - File. 
	 * @return List<Address> A list of <b>Logical</b> addresses
	 */
	public static List<Address> readAddressesFromFile (File f)  {
		
		List<Address> addressList = new ArrayList<>(100);
		try (BufferedReader fr = new BufferedReader( new FileReader(f) )) {

			String line = fr.readLine();
		    while( line != null ) {
		    	//Java's ints are 32 bits
		    	String[] addBit = line.split(" ");
		    	Address addr = null;
		    	if (addBit.length > 1) {
		    		Integer i = Integer.valueOf(addBit[0]);
		    		String bit = addBit[1];
		    		ReadWriteBit rwBit = ReadWriteBit.parse(bit);
		    		addr = new LogicalAddress(i, rwBit);
		    	} else { 
		    		Integer i = Integer.valueOf(addBit[0]);
		    		addr = new LogicalAddress(i);
		    	}
		    	
		    	addressList.add(addr);
		        line = fr.readLine();
		    }

		} catch (Exception e) {
			System.err.print(e);
		}
		return addressList;
	}
	
	/**
	 * Used for a string comparison to ensure that the
	 * output created by this program matches the expected output.
	 * 
	 * @param f File - "correct.txt"
	 * @return the contents of the file as a String.
	 */
	public static String readExpectedOutputFromFile (File f) {
		
		StringBuilder sb = new StringBuilder();
		
		try (BufferedReader fr = new BufferedReader( new FileReader(f) )) {

			String line = fr.readLine();
		    while( line != null ) {
		    	sb.append(line);
		    	sb.append("\n");
		        line = fr.readLine();
		    }

		} catch (Exception e) {
			System.err.print(e);
		}
		return sb.toString();
		
	}

}
